package org.example.jol;

public class WaitTest {

    public static Object NOT_FULL = new Object();

    public static Object NOT_EMPTY = new Object();

    public static Object LOCK = new Object();

    public static Integer counter = 0;

    // 容量为0
    public static final Integer CAPACITY = 100;

    public static void main(String[] args) {
        // 1个生产者 10个消费者
        new ProducerThread().start();

        for (int i = 0; i < 10; i++) {
            new ConsumerThread().start();
        }
    }

    // 生产者线程
    static class ProducerThread extends Thread {
        @Override
        public void run() {
            try {
                // 2. 判断苹果有没有满了
                // 3. 如果满了，就地等待，等待未满通知
                // 4. 如果没有满，继续生成苹果
                while (true) {
                    while (counter > CAPACITY) {
                        synchronized (NOT_FULL) {
                            NOT_FULL.wait();
                        }
                    }

                    synchronized (LOCK) {
                        System.out.println("生产苹果：" + (++counter));
                    }
                    synchronized (NOT_EMPTY) {
                        NOT_EMPTY.notify();
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 消费者线程
    static class ConsumerThread extends Thread {
        @Override
        public void run() {
            try {
                // 2. 判断苹果还有没有
                // 3. 如果有，就获取一个苹果
                // 4. 如果没有，就此等待，等非空通知
                while (counter <= 0) {
                    // 就地等待
                    synchronized (NOT_EMPTY) {
                        NOT_EMPTY.wait();
                    }
                }

                synchronized (LOCK) {
                    System.out.println("消费苹果：" + counter);
                    counter--;
                }
                synchronized (NOT_FULL) {
                    NOT_FULL.notify();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
